#pragma once
#include "Randomizer.h"
#include "Vector3D.h"
#include "Stdafx.h"
#include "Particle.h"

namespace Pulpy
{
	class ParticleSystem
	{
	private:
		int _MaxParticles;
		Particle * _ParticleList;
		Vector3D<float> _Emitter;
		Vector3D<float> _Speed;
		int _EmitRatePerSecond;
		int _ShownParticle;
		bool _GravityPull;
		float _Life;
		void (*particleDraw)();
		float _XFac;
		float _YFac;
		float _ZFac;
		float _SXFac;
		float _SYFac;
		float _SZFac;
		Particle newParticle() 
		{ 
			Vector3D<float> s(Randomizer::getInstance().randMax(_SXFac), Randomizer::getInstance().randMax(_SYFac), Randomizer::getInstance().randMax(_SZFac));
			Vector3D<float> v(Randomizer::getInstance().randMax(_XFac), Randomizer::getInstance().randMax(_YFac), Randomizer::getInstance().randMax(_ZFac));
			return Particle(_Emitter+s, _Speed+v, _Life); 
		}
	public:
		ParticleSystem(): _MaxParticles(0), _EmitRatePerSecond(0), _ShownParticle(0),_Life(0), _GravityPull(false) { }
		ParticleSystem(int max, int rate, float life, bool drop, const Vector3D<float> &speed, const Vector3D<float> &pos): 
		_MaxParticles(max), _ShownParticle(0), _GravityPull(drop), _Life(life)
		{ _ParticleList = new Particle[max]; _Emitter = pos; _Speed = speed; _EmitRatePerSecond = _MaxParticles / rate; }
		~ParticleSystem() { delete [] _ParticleList; }
		void init(void (*drawFunc)(), float xfac = 0, float yfac = 0, float zfac = 0, float sxfac = 0, float syfac = 0, float szfac = 0)
		{
			particleDraw = drawFunc;
			_XFac = xfac;
			_YFac = yfac;
			_ZFac = zfac;
			_SXFac = sxfac;
			_SYFac = syfac;
			_SZFac = szfac;
			for(int i = 0; i < _MaxParticles; ++i)
			{
				_ParticleList[i] = newParticle();
			}
		}
		void toggleGravity()
		{
			_GravityPull = !_GravityPull;
		}
		void drawParticle()
		{
			for(int i=0; i < _ShownParticle; ++i)
			{
				_ParticleList[i].draw(particleDraw);
			}
		}
		void update()
		{
			for(int i=0; i < _ShownParticle; ++i)
			{
				_ParticleList[i].update(_GravityPull);
				if(_ParticleList[i].getLife() <= 0)
					_ParticleList[i] = newParticle();
			}
			if(_ShownParticle < _MaxParticles)
				_ShownParticle += _EmitRatePerSecond;
		}
	};
}